﻿using System.Collections;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;

public class CustomVisionAnalyser : MonoBehaviour
{

    public static CustomVisionAnalyser Instance;
    private string predictionEndpoint = "http://192.168.4.133:8989/file/upload";

    private void Awake()
    {
        Instance = this;
    }

    /// <summary>
    /// Call the Computer Vision Service to submit the image.
    /// 
    /// HoloLens中截取一个图片然后触发传递到service服务器上
    /// </summary>
    public IEnumerator AnalyseLastImageCaptured(byte[] imageBytes)
    {
        WWWForm webForm = new WWWForm();

        // 将图片byte数组添加进表单
        webForm.AddBinaryData("file", imageBytes, "photo.jpg");

        // 将图片上传到服务器
        using (UnityWebRequest unityWebRequest = UnityWebRequest.Post(predictionEndpoint, webForm))
        {
            // The download handler will help receiving the analysis from Azure
            unityWebRequest.downloadHandler = new DownloadHandlerBuffer();

            // Send the request
            yield return unityWebRequest.SendWebRequest();

            if (unityWebRequest.isHttpError || unityWebRequest.isNetworkError)
            {
                Debug.Log(unityWebRequest.error);
            }
            else
            {
                string response = unityWebRequest.downloadHandler.text;
                Debug.Log(response);
            }
        }
    }
}
